<?
class User 
{

  var $preferred_products = array();
  var $enabled = 1;

  function __construct($username)
  {
    $this->name = $username;
  }

  public static function query_database($query)        //       
  {                                                    //  All this is
    $dbh = new PDO ('sqlite:/var/www/database.db');    //  duplicate code 
    $result = $dbh->query($query);                     //  in Products.class.php
    $rows = $result->fetchAll();                       //
    return $rows;                                      //
  }                                                    //  Dont do this in real life!
                                                       // 
  public static function exec_database($to_exec)       // 
  {                                                    // 
    $dbh = new PDO ('sqlite:/var/www/database.db');    // 
    $result = $dbh->exec($to_exec);                    //
    return $result;                                    // 
  }                                                    //      



  function set_enable($state)
  {
    if ($state=="enabled" || $state == TRUE || $state == 1)
      {$this->enabled = 1;}
    else
      {$this->enabled = 0;}
    // Then call $this->save() to write in the databse
  }
  
  function set_from_database()
  {
    $me=self::query_database("SELECT username, enabled FROM users WHERE username = '".$this->name."' ");
    $this->enabled        = $me[0]['enabled'];
  }
  

  function set_from_web_post($the_request) // A HTTP Request
  {
    $this->set_enable($the_request['enabled']);
  }

  function to_html()
  {
    print "<ul>";

    print "<li>".$this->name        ."";
    print ($this->enabled)?"<li> enabled </li>":"<li> disabled </li>";
    print "</ul>";
  }

  function save()
  {
    // Create & Save in one function
    $rows = self::query_database("SELECT username,enabled FROM users WHERE username = '". $this->name."'");
    if ($rows)
      {
        // The SELECT returned more than 0 results => UPDATE
        // http://www.sqlite.org/lang_update.html
        $result = self::exec_database("UPDATE users SET username='".$this->name."', 
                                                        enabled = '".$this->enabled."' 
                                       WHERE username = '".$this->name."'");
      }
    else
      {
        // The SELECT returned 0 result => INSERT
        // http://www.sqlite.org/lang_insert.html
        $result = self::exec_database("INSERT INTO users VALUES ('".$this->name."', 1)");
      }
  }
  
  function get_name()
  {
    return $this->name;
  }


}
?>
